package com.zifan.sever.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zifan.sever.bean.MenuRole;
import com.zifan.sever.mapper.MenuRoleMapper;
import com.zifan.sever.service.IMenuRoleService;
import com.zifan.sever.utils.RespBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zifan
 * @since 2021-04-10
 */
@Service
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRole> implements IMenuRoleService {

    /**
     * 查出该角色id对应的菜单列表
     * @param rid
     * @return
     */
    @Override
    public List<Integer> getMenusIdByRoleId(Integer rid) {
        QueryWrapper<MenuRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MenuRole::getRid,rid);
        return this.list(wrapper)
                .stream()
                .map(MenuRole::getMid)
                .collect(Collectors.toList());
    }

    /**
     * 更新角色的菜单列表，
     * @param rid
     * @param mids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RespBean updateRolesMenu(Integer rid, Integer[] mids) {
        //先删除该角色下的所有菜单
        QueryWrapper<MenuRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MenuRole::getRid,rid);
        this.remove(wrapper);
        //删除之后，如果mids为空，就说明没有要添加的，就只删除就好了，直接返回
        if (null == mids || mids.length == 0){
            return RespBean.success("操作成功");
        }
        //todo 这里可以使用流式编程，有空试一试
        if (baseMapper.updateRolesMenu(rid,mids) != 0){
            return RespBean.success("操作成功");
        }
        return RespBean.error("操作失败");
    }
}
